package com.qysoft.modules.common.util;

import com.jfinal.kit.PathKit;
import com.jfinal.upload.UploadFile;
import com.qysoft.modules.common.contants.Contants;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.UUID;

/**
 * Created by zj on 2018/4/12. 文件上传
 */
public class FileUploadUtil {

	public static String uploadFile(HttpServletRequest request, UploadFile file) {

		if (file == null) {
			return "";
		} else {
			String fileName = file.getFileName();
			String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
			String path = Contants.UPLOAD_PATH + UUID.randomUUID().toString() + "." + suffix;
			String filePath = PathKit.getWebRootPath() + path;
			file.getFile().renameTo(new File(filePath));
			String viewPath = request.getContextPath() + path;
			return viewPath;
		}
	}

	/**
	 * xuelin 上传附件
	 * 
	 * @param file
	 *            uploadSubfolder 上传文件要存放的子文件夹，如/upload/pic或upload/file
	 * @return
	 */

	public static String uploadfj(UploadFile file, String uploadSubfolder) {

		if (file == null) {
			return "";
		} else {
			try {
				String contextPath = PathKit.getWebRootPath();
				String fileName = file.getFileName();
				String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
				String path = uploadSubfolder + UUID.randomUUID().toString() + "." + suffix;
				//检查创建目录
				String filedir = contextPath + uploadSubfolder;
				
				File sfolder = new File(filedir);
				if (!sfolder.exists()) {
					sfolder.mkdirs();
				}
				contextPath = contextPath + path;
				file.getFile().renameTo(new File(contextPath));
				return path;
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
		return "";
	}

}
